<template>
  <div class="box">
    <div class="dz">{{title}}3.0级以上地震：{{ total }}个</div>
    <div class="fb">
      <div class="t1">{{title}}地震分布</div>
      <div class="t2">{{ time }}</div>
    </div>
    <div class="chartbox" ref="chartRef"> </div>
    <el-button type="primary" @click="back" class="pt" v-show="flag">返回</el-button>
  </div>
</template>  
  
<script setup>
import { useRoute, useRouter } from 'vue-router'
import { ref, onMounted, onUnmounted, defineExpose, defineEmits } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/modules/user'

const store = useUserStore();
const userCode = store.userInfo.divisionCode;

const chartRef = ref(null)
const flag = ref(false)
let myChart = null
const router = useRouter()

const emits = defineEmits(['updateCity'])

var option = {
  tooltip: {
    trigger: 'item', // 触发类型：数据项图形触发
    formatter: function (e) {
      return `地点<br />${e.data.name} :${e.data.value[2]}级`
    }
  },
  visualMap: {
    seriesIndex: 0,
    left: 'left', // 根据实际情况调整位置
    bottom: 'bottom', // 根据实际情况调整位置
    textStyle: {
      color: '#fff' // 设置文字颜色为白色
    },
    pieces: [
      {
        gte: 3.0,
        lte: 3.9,
        label: '3.0 - 3.9',
        symbol: 'circle',
        symbolSize: [12, 12],
        textStyle: {
          color: '#fff'
        },
        itemStyle: { color: '#7b91d3', borderColor: '#FFFFFF', borderWidth: 1 }
      },
      {
        gte: 4.0,
        lte: 4.9,
        label: '4.0 - 4.9',
        symbol: 'circle',
        textStyle: {
          color: '#fff'
        },
        symbolSize: [16, 16],
        itemStyle: { color: '#91cc75', borderColor: '#FFFFFF', borderWidth: 1 }
      },
      {
        gte: 5,
        label: '5.0+',
        symbol: 'circle',
        symbolSize: [24, 24],
        itemStyle: { color: '#fac858', borderColor: '#FFFFFF', borderWidth: 1 }
      }
    ],
    inRange: {
      color: ['#91cc75', '#fac858', '#ff2f14']
    }
  },
  geo: {
    map: 'china', // 使用的地图类型
    roam: true, // 是否允许缩放和平移
    label: {
      emphasis: {
        show: true,
        color: '#fff'
      }
    },
    itemStyle: {
      normal: {
        borderColor: '#02AAF6', // 默认边界线颜色设置为透明
        borderWidth: 1, // 默认边界线宽度
        areaColor: '#12419B'
      },
      emphasis: {
        areaColor: '#0e9cff', // 悬停时区域填充颜色（这里设置为白色，实际可设为透明或其他颜色）
        borderColor: '#0e9cff', // 悬停时边界线颜色
        borderWidth: 2 // 悬停时边界线宽度
      }
    }
  },
  series: [
    {
      name: '地点',
      type: 'scatter', // 图表类型为效果散点图
      coordinateSystem: 'geo' // 使用地理坐标系
    }
  ]
}

const init = (e) => {
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
  myChart = echarts.init(chartRef.value)
  var data = []
  for (const item of e) {
    data.push({
      name: item.province,
      id: item.id,
      value: [item.longitude, item.dimensionality, item.shockLevel]
    })
  }
  option.series[0].data = data

  myChart.setOption(option)
  myChart.on('click', getNextData)
}

let aaa = false

const getNextData = (params) => {
  console.log(params);
  
  // 获取点击的省份名称
  const provinceName = params.name
  var a = jsonObj.features.filter((e) => {
    return e.properties.name === provinceName
  })

  if (a && a.length > 0 && userCode == 'root') {
    // 获取该省份下的所有城市
    fetch(`/static/map-geojson/${a[0].properties.adcode}.json`)
      .then((e) => {
        return e.json()
      })
      .then((e) => {
        echarts.registerMap(provinceName, e)
        option.geo.map = provinceName
        flag.value = true
        emits('updateCity', provinceName)
      })
  } else {
    var eqid = params.data.id
    router.push({
      path: '/gis/bigscreen',
      query: {
        beforePath: router.currentRoute.value.path,
        data: JSON.stringify({
          id: eqid
        })
      }
    })
  }
}
var jsonObj = null
// 初始化图表
const initChart = (data) => {
  if (jsonObj) {
    option.geo.map = 'china'
    echarts.registerMap('china', jsonObj)
    init(data)
    return
  }
  if (chartRef.value) {
    var user = userCode == 'root' ? 'china' : userCode
    fetch(`/static/map-geojson/${userCode == 'root' ? 'china' : userCode}.json`)
      .then((e) => {
        return e.json()
      })
      .then((e) => {
        jsonObj = e
        option.geo.map = userCode
        echarts.registerMap(userCode, e)
        init(data)
      })
  }
}

const total = ref(0)
const time = ref('')
const title = ref('')
const getData = (data, d2, d3) => {
  title.value =d3.name;
  total.value = 0
  for (const i of d2.chartData) {
    for (const element of i.data) {
      total.value = total.value + element || 0
    }
  }

  switch (d3.type) {
    case 0:
      time.value =
        dayjs(d3.startTime, 'YYYY').format('YYYY年') +
        '-' +
        dayjs(d3.endTime, 'YYYY').format('YYYY年')
      break
    case 1:
      time.value =
        dayjs(d3.startTime, 'YYYYMM').format('YYYY年MM月') +
        '-' +
        dayjs(d3.endTime, 'YYYYMM').format('YYYY年MM月')
      break
    case 2:
      time.value =
        dayjs(d3.startTime, 'YYYYMMDD').format('YYYY年MM月DD日') +
        '-' +
        dayjs(d3.endTime, 'YYYYMMDD').format('YYYY年MM月DD日')
      break
  }
  if (flag.value) {
    updateData(data)
    return
  }
  initChart(data)
}

const updateData = (e) => {
  var data = []
  for (const item of e) {
    data.push({
      name: item.province,
       id: item.id,
      value: [item.longitude, item.dimensionality, item.shockLevel]
    })
  }
  option.series[0].data = data
  myChart.setOption(option)
}

const back = () => {
  flag.value = false
  emits('updateCity', '')
}

// 主动暴露childMethod方法
defineExpose({ getData })

// 组件挂载后初始化图表
onMounted(() => {
  window.addEventListener('resize', () => {
    myChart && myChart.resize()
  })
})

// 组件卸载时销毁图表实例，避免内存泄漏
onUnmounted(() => {
  myChart && myChart.dispose()
})
</script>  
  
<style lang="scss" scoped>
.chartbox,
.box {
  height: 100%;
  position: relative;
  .fb {
    width: 27.03vw;
    position: absolute;
    z-index: 9;
    left: 50%;
    top: 120px;
    transform: translateX(-50%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .t1 {
      font-size: 1.6666vw;
      font-weight: bold;
      color: #ffffff;
      margin-bottom: 16px;
    }
    .t2 {
      font-size: 1.25vw;
      font-weight: bold;

      color: #11f6f2;
    }
  }
  .dz {
    width: 28.03vw;
    height: 8.8vh;
    z-index: 9;
    background-image: url(/static/assets/centerbox.png);
    background-repeat: no-repeat;
    background-size: 100% 100%;
    position: absolute;
    left: 50%;
    top: 20px;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.6666vw;
    font-weight: bold;
    color: #f9fdff;
  }
}
.pt {
  position: absolute;
  right: 15px;
  bottom: 15px;
  width: 92px;
  height: 36px;
  background-image: url(/static/assets/tbtn.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;

  display: flex;
  align-items: center;
  font-size: 14px;
  color: #01c2ff;
  line-height: 24px;
  cursor: pointer;
}
</style>